package admin

import (
	"gf/library/common"
	"gf/library/response"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"path"
	"strings"
)

var File = fileApi{}

type fileApi struct {
}

func (a *fileApi) Upload(r *ghttp.Request) {
	file := r.GetUploadFile("upload-file")

	t := gtime.Now()
	date := t.Format("Y-m-d")

	filename, err := file.Save("./public/uploads/" + date)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}

	ext := path.Ext(filename)
	split := strings.Split(ext, ".")
	suffix := split[len(split)-1]
	suffix = strings.ToLower(suffix)

	size := common.FormatFileSize(file.Size)
	res := struct {
		Ext      string
		Filename string
		Size     string
		Path     string
	}{Ext: suffix, Filename: filename, Size: size , Path: "/public/uploads/" + date + "/" + filename}

	response.JsonExit(r, 0, "ok", res)
}
